package Top_Interview_Questions_Review._007Sliding_Window;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @Author: 吕庆龙
 * @Date: 2020/3/15 12:16
 * <p>
 * 功能描述:
 */
public class _0239 {

    public static void main(String[] args) {
        _0239 test = new _0239();
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        int[] window = test.maxSlidingWindow1(nums, 3);
        System.out.println(window);
    }


    /**
     * 输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
     * 输出: [3,3,5,5,6,7]
     * 解释:
     * <p>
     * 滑动窗口的位置                最大值
     * ---------------               -----
     * [1  3  -1] -3  5  3  6  7       3
     * 1 [3  -1  -3] 5  3  6  7       3
     * 1  3 [-1  -3  5] 3  6  7       5
     * 1  3  -1 [-3  5  3] 6  7       5
     * 1  3  -1  -3 [5  3  6] 7       6
     * 1  3  -1  -3  5 [3  6  7]      7
     */
    public int[] maxSlidingWindow(int[] nums, int k) {

        if (nums.length == 0) {
            return new int[0];
        }
        int left = 0;
        int right = k - 1;
        int[] res = new int[nums.length - k + 1];
        while (right < nums.length) {
            res[left] = Integer.MIN_VALUE;
            for (int i = left; i <= right; i++) {
                res[left] = Math.max(res[left], nums[i]);
            }
            left++;
            right++;
        }
        return res;
    }

    /**
     * https://leetcode-cn.com/problems/sliding-window-maximum/solution/dan-diao-dui-lie-by-labuladong/
     */
    public int[] maxSlidingWindow1(int[] nums, int k) {
        int n = nums.length;
        if (n * k == 0) return new int[0];

        MonotonicQueue window = new MonotonicQueue();
        int[] res = new int[nums.length - k + 1];
        int index = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i < k - 1) { //先填满窗口的前 k - 1
                window.push(nums[i]);
            } else { // 窗口向前滑动
                window.push(nums[i]);
                res[index++] = window.max();
                window.pop(nums[i - k - 1]);
            }
        }
        return res;

    }
}

class MonotonicQueue {
    private Deque<Integer> data = new ArrayDeque<>();
    public void push(int n) {
        while (!data.isEmpty() && data.getLast() < n)
            data.removeLast();
        data.addLast(n);
    }

    int max() { return data.getFirst(); }

    void pop(int n) {
        if (!data.isEmpty() && data.getFirst() == n)
            data.removeFirst();
    }


}






